package com.pfzy.utildemo.activity.record.soundrecord.upload.qiniu;

import android.os.Handler;
import android.os.Looper;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pfzy.lib.common.UserConfig;
import com.pfzy.lib.common.http.CCCXSubscriber;
import com.pfzy.lib.config.ConstValue;
import com.pfzy.lib.net.ObservableProxy;
import com.pfzy.utildemo.activity.record.soundrecord.UxSoundRecordApi;
import com.pfzy.utildemo.activity.record.soundrecord.upload.Dto.UploadAudioInfo;
import com.pfzy.utildemo.activity.record.soundrecord.upload.callback.UploadCallback;
import com.pfzy.utildemo.api.ApiHelper;
import com.pfzy.utildemo.bean.TokenBean;
import com.pfzy.lib.config.log.MyLog;
import com.pfzy.utildemo.utils.CommonUtil;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

public class QiniuCenter {
    private static final String RESUME_CACHE_NAME = "qiniu_resume_cache";// 恢复_缓存
    private static QiniuCenter mInstance;
    private UploadManager uploadManager;
    private ApiHelper mApiHelper;
    private static ArrayList<String> mUploadingList = new ArrayList<>();
    private final Handler mHandler = new Handler(Looper.getMainLooper());

    public static QiniuCenter getInstance() {
        if (mInstance == null) {
            synchronized (UxSoundRecordApi.class) {
                if (mInstance == null) {
                    mInstance = new QiniuCenter();
                }
            }
        }
        return mInstance;
    }

    private QiniuCenter() {
        // 七牛上传文件管理类
        uploadManager = new UploadManager(new Configuration.Builder().build());
        mApiHelper = new ApiHelper();
    }

    public void uploadFile(UploadAudioInfo info, UploadCallback callback) {
        TokenBean qiniu = UserConfig.getQiniuToken();
        if (qiniu.getToken().length() > 0) {
            getQiniuInfoSuccess(info, callback, qiniu);
        } else {
            initQiniuToken();
        }
    }

    /**
     * 上传录音文件
     */
    private void initQiniuToken() {
        ObservableProxy
                .createProxy(mApiHelper.getQiniuToken())
                .subscribe(new CCCXSubscriber<JSONObject>(true) {
                    @Override
                    public void onCCSuccess(final JSONObject data) {
                        String json = data.toJSONString();
                        Gson gson = new GsonBuilder().serializeNulls().create();
                        TokenBean qiniu = gson.fromJson(json, TokenBean.class);
//                        AudioManager.getInstance(mContext).startRecord(driverId, orderId);
                    }

                    @Override
                    public void onFailed(int code, String message) {

                    }
                });
    }

    public void getQiniuInfoFailed(UploadAudioInfo info, UploadCallback callback, int errorCode, String message) {
        callback.onFailed(info, errorCode, message);
    }

    public void getQiniuInfoSuccess(UploadAudioInfo info, UploadCallback callback, TokenBean qiniuInfo) {
        mUploadingList.add(info.getUid());
        uploadResumeUpload(info, callback, qiniuInfo, info.getFilePathList().get(0));
    }

    private void uploadResumeUpload(final UploadAudioInfo info, final UploadCallback callback, TokenBean qiniuInfo, String filePath) {
        File recordDir = new File(CommonUtil.getContext().getCacheDir(), RESUME_CACHE_NAME);
        if (!recordDir.exists()) {
            recordDir.mkdirs();
        }

        long timeMill = System.currentTimeMillis();
        Long timeOp = timeMill / 1000;
        String date = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(timeMill);
        String keyname = ConstValue.QINIU_AUDIO_FORMAT + date + "/" + timeOp + ".aac";

        uploadManager.put(filePath, keyname, qiniuInfo.getToken(), new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo res, org.json.JSONObject response) {
                if (res.isOK()) {
                    _logd("Upload Success" + response.toString());
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onCompleteSuccess(info, info.getFilePathList());
                        }
                    });
                } else {
                    callback.onFailed(info, res.statusCode, res.error);
                }
            }
        }, new UploadOptions(null, null, false, new UpProgressHandler() {
            @Override
            public void progress(String key, double percent) {
                _logd("key: " + key + "percent: " + percent);
            }
        }, null));
    }

    private void _logd(String msg) {
        MyLog.logd("七牛中心 " + msg);
    }

    private void _loge(String msg) {
        MyLog.loge("七牛中心 " + msg);
    }
}
